package com.dj.mingkong.common.util;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.Map.Entry;

public class HttpUtils {
    public static final String DEFAULT_CHARSET = "UTF-8";
    private static Logger log = LoggerFactory.getLogger(HttpUtils.class);
    private static CloseableHttpClient httpClient;
    private static PoolingHttpClientConnectionManager cm;
    private static RequestConfig requestConfig;
    private static ResponseHandler<HttpObj> responseHandler = null;

    public HttpUtils() {
    }

    private static SSLConnectionSocketFactory createSSLConnectionSocketFactory() {
        TrustManager manager = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        SSLConnectionSocketFactory factory = null;

        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init((KeyManager[]) null, new TrustManager[]{manager}, (SecureRandom) null);
            factory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return factory;
    }

    private static void shutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread("thread-http.shutdown") {
            public void run() {
                try {
                    HttpUtils.httpClient.close();
                } catch (IOException var2) {
                    HttpUtils.log.error("httpClient 关闭失败", var2);
                }

            }
        });
    }

    public static HttpObj get(String url) {
        return get(url, (Map) null);
    }

    public static HttpObj get(String url, Map<String, Object> params) {
        return getHttpObj(url, params, (Map) null);
    }

    public static HttpObj get(String url, Map<String, Object> params, Map<String, String> headers) {
        return getHttpObj(url, params, headers);
    }

    public static HttpObj getHttpObj(String url, Map<String, Object> params, Map<String, String> headers) {
        if (params != null && params.size() > 0) {
            List<NameValuePair> nvps = new ArrayList(params.size());
            Iterator var4 = params.entrySet().iterator();

            while (var4.hasNext()) {
                Entry<String, Object> param = (Entry) var4.next();
                nvps.add(new BasicNameValuePair((String) param.getKey(), param.getValue().toString()));
            }

            String queryString = URLEncodedUtils.format(nvps, "UTF-8");
            url = url + "?" + queryString;
        }

        HttpGet get = new HttpGet(url);
        get.setConfig(requestConfig);
        return execute(get, headers);
    }

    public static HttpObj post(String url, Map<String, Object> params) {
        return post(url, (Map) params, (Map) null);
    }

    public static HttpObj post(String url, Map<String, Object> params, Map<String, String> headers) {
        UrlEncodedFormEntity entity = null;
        if (params != null && params.size() > 0) {
            List<NameValuePair> nvps = new ArrayList(params.size());
            Iterator var5 = params.entrySet().iterator();

            while (var5.hasNext()) {
                Entry<String, Object> param = (Entry) var5.next();
                nvps.add(new BasicNameValuePair((String) param.getKey(), param.getValue().toString()));
            }

            entity = new UrlEncodedFormEntity(nvps, Charset.forName("UTF-8"));
        }

        return post(url, (HttpEntity) entity, headers);
    }

    public static HttpObj postJson(String url, String body) {
        return postJson(url, body, (Map) null);
    }

    public static HttpObj postJson(String url, String body, Map<String, String> headers) {
        StringEntity entity = new StringEntity(body, "UTF-8");
        entity.setContentType("application/json");
        return post(url, (HttpEntity) entity, headers);
    }

    public static HttpObj postForm(String url, Map<String, String> bodyParam, Map<String, String> headers) {
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
        if (MapUtils.isNotEmpty(bodyParam)) {
            List<NameValuePair> params = new ArrayList();
            bodyParam.forEach((k, v) -> {
                params.add(new BasicNameValuePair(k, v));
            });

            try {
                post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            } catch (UnsupportedEncodingException var6) {
                log.error("不支持的类型解析", var6);
            }
        }

        return execute(post, headers);
    }

    private static HttpObj post(String url, HttpEntity entity, Map<String, String> headers) {
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
        if (entity != null) {
            post.setEntity(entity);
        }

        return execute(post, headers);
    }

    public static HttpObj patchJson(String url, String body, Map<String, String> headers) {
        StringEntity entity = new StringEntity(body, "UTF-8");
        entity.setContentType("application/json");
        return patch(url, entity, headers);
    }

    private static HttpObj patch(String url, HttpEntity entity, Map<String, String> headers) {
        HttpPatch patch = new HttpPatch(url);
        patch.setConfig(requestConfig);
        if (entity != null) {
            patch.setEntity(entity);
        }

        return execute(patch, headers);
    }

    private static HttpObj execute(HttpUriRequest req, Map<String, String> headers) {
        if (headers != null && headers.size() > 0) {
            Iterator var2 = headers.entrySet().iterator();

            while (var2.hasNext()) {
                Entry<String, String> entry = (Entry) var2.next();
                req.setHeader((String) entry.getKey(), (String) entry.getValue());
            }
        }

        String traceId = ThreadContext.get("req.requestId");
        if (StringUtils.isNotBlank(traceId)) {
            req.setHeader("req.requestId", traceId);
        }

        try {
            return (HttpObj) httpClient.execute(req, responseHandler);
        } catch (IOException var4) {
            throw new RuntimeException(var4);
        }
    }

    static {
        //Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", createSSLConnectionSocketFactory()).build();
        requestConfig = RequestConfig.custom().setCookieSpec("standard-strict").setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList("NTLM", "Digest")).setProxyPreferredAuthSchemes(Arrays.asList("Basic")).build();
        //cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setMaxTotal(50);
        cm.setDefaultMaxPerRoute(10);
        cm.closeExpiredConnections();
        cm.setValidateAfterInactivity(2000);
        httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(5000).build()).build();
        responseHandler = new ResponseHandler<HttpObj>() {
            public HttpObj handleResponse(HttpResponse httpResponse) throws IOException {
                StatusLine statusLine = httpResponse.getStatusLine();
                HttpEntity entity = httpResponse.getEntity();
                byte[] bodyBytes;
                if (entity != null) {
                    bodyBytes = EntityUtils.toByteArray(entity);
                } else {
                    bodyBytes = new byte[0];
                }

                HttpObj resp = new HttpObj();
                resp.setStatusCode(statusLine.getStatusCode());
                resp.setBody(new String(bodyBytes, "UTF-8"));
                return resp;
            }
        };
        shutdownHook();
    }
}
